import os
from starlette.config import Config
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from model.ModWorkRecord import WorkRecord
from model.ModPhotoIndex import PhotoIndex


_config = Config("deploy_config.env")
DATABASE_URL = _config("DATABASE_URL")
engine = create_engine(DATABASE_URL)
Session = sessionmaker(bind=engine)


if __name__ == '__main__':
    if not os.path.exists("./sorted_photos"):
        os.mkdir("./sorted_photos")

    session = Session()

    try:
        records = session.query(WorkRecord).all()
        photos = session.query(PhotoIndex).all()

        for rec in records:
            target_path = os.path.join("./sorted_photos", rec.bureauname, rec.openname)
            if not os.path.exists(target_path):
                os.makedirs(target_path)

            photo = next((p for p in photos if p.photo_fingerprint == rec.photo_fingerprint), None)
            if photo is not None:
                source = os.path.join("./uploads", photo.access_path)
                destination = os.path.join(target_path, f"{rec.stationname}-{rec.serial_number}-{photo.access_path}")
                if not os.path.exists(source):
                    print(f"{source} 不存在，跳过。")
                    continue
                if os.path.exists(destination):
                    print(f"{source} 对应的文件已存在，跳过。")
                    continue
                print(f"{source} -> {destination}")
                with open(destination, "wb") as dest:
                    with open(source, "rb") as sour:
                        dest.write(sour.read())
    finally:
        session.rollback()
        session.close()
